package dao;

import beans.User;
import db.DBQuery;
import db.RedisQuery;
import utils.CommonUtils;
import utils.KeyUtils;
import utils.MD5Utils;

import java.util.List;

public class UserDAO extends CommonDAO<User> {

    public final static UserDAO ME = new UserDAO();

    @Override
    protected String tableName() {
        return new User().tableName();
    }

    public User getByAccount(String account) {
        String sql = "select * from " + tableName() + " where account=? limit 1";
        return DBQuery.read_bean(User.class, sql, account);
    }

    public boolean checkUserPwd(String account, String hashPwd) {
        String sql = "select pwd from " + tableName() + " where account=? limit 1";
        String realHashPwd = DBQuery.read_scalar(sql, account);
        return hashPwd.equals(realHashPwd);
    }

    public String setUserToken(User user) {
        String key = getRedisSavePath("UserToken") + user.getId();
        String token = MD5Utils.md5(user.getAccount(), KeyUtils.USER_TOKEN_KEY) +
                CommonUtils.getCurrentTime("yyyyMMddHHmmssSSS") +
                CommonUtils.getRandomSixFigure();
        RedisQuery.set(key, token);
        return token;
    }

    public String readUserToken(long userId) {
        String key = getRedisSavePath("UserToken") + userId;
        return RedisQuery.getByKey(key);
    }

}
